<?php


namespace app\user\logic;

//负责登录的类
use app\http\middleware\checkTTUserToken;
use app\http\middleware\checkUserToken;
use app\user\model\User as UserModel;
use think\Facade;
use think\facade\Config;

class LoginMiniProgram
{

    protected $type;
    protected $appid;
    protected $secret;

    public function __construct($type)
    {
         $this->type = $type;
         $this->appid=Config::get('miniprogram.wx.appid') ;
         $this->secret=Config::get('miniprogram.wx.secret')    ;
    }

    //根据code获取用户信息
    public function login($code)
    {
        switch ($this->type) {
            //微信登录的
            case 'wx':
                $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$code}&grant_type=authorization_code";
                break;
            case 'tt':
                $api = "http://developer.toutiao.com/api/apps/jscode2session?appid={$this->appid}&secret={$this->secret}&code={$code}";
                break;
            default:
                exception('type参数错误');
        }

        $res = httpGet($api);
        return json_decode($res);
    }


    public function miniProLogin($type, $openid)
    {
        //判断账号是否已经注册了
        $user = UserModel::where($type . '_openid', $openid)->field('password', true)->find();
        if ($user) {
            $data = [
                "token" => checkTTUserToken::issueToken($user)
            ];

            return $data;
//          return  $this->result(200, $data, '登陆成功');

        } else {

            //还没有账号，注册一个默认的
            $user = UserModel::create([
                'username' => '用户' . rand(10000, 99999),
                'password'=>$openid,
                "add_time" => time(),
                $type . '_openid' => $openid
            ]);

            //判断是否注册成功
            if ($user) {
                $user2 = UserModel::where($type . '_openid', $openid)->field('password', true)->find();
                $data = [
                    "token" => checkTTUserToken::issueToken($user2)
                ];
                return $data;
//                return toResful(200, $data, '首次登录，注册成功');
            } else {
                exception('登录注册失败');
//                return toResful(400, $user, '注册失败');
            }
        }
    }


}
